#!/bin/bash

# ERP Mock Server 快速更新部署脚本
# 使用方法: bash update_deploy.sh

echo "🚀 开始 ERP Mock Server 更新部署..."
echo "=================================================="

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置变量
APP_DIR="/opt/erp-mock"
SERVICE_NAME="erp-mock"
BACKUP_DIR="/tmp/erp-mock-backup-$(date +%Y%m%d_%H%M%S)"

# 检查是否为root用户
check_root() {
    if [[ $EUID -eq 0 ]]; then
        echo -e "${RED}❌ 请不要使用root用户运行此脚本${NC}"
        exit 1
    fi
}

# 检查必要的目录和文件
check_prerequisites() {
    echo -e "${BLUE}🔍 检查前置条件...${NC}"

    if [ ! -d "$APP_DIR" ]; then
        echo -e "${RED}❌ 应用目录不存在: $APP_DIR${NC}"
        exit 1
    fi

    if [ ! -d "$APP_DIR/.git" ]; then
        echo -e "${RED}❌ Git仓库未初始化，请使用手动部署方式${NC}"
        exit 1
    fi

    echo -e "${GREEN}✅ 前置条件检查通过${NC}"
}

# 创建备份
create_backup() {
    echo -e "${BLUE}📦 创建备份...${NC}"
    mkdir -p "$BACKUP_DIR"

    # 备份关键文件
    cp -r "$APP_DIR/app" "$BACKUP_DIR/"
    cp -r "$APP_DIR/static" "$BACKUP_DIR/"
    cp "$APP_DIR/main.py" "$BACKUP_DIR/"

    echo -e "${GREEN}✅ 备份创建完成: $BACKUP_DIR${NC}"
}

# 停止服务
stop_service() {
    echo -e "${BLUE}🛑 停止服务...${NC}"

    if systemctl is-active --quiet $SERVICE_NAME; then
        sudo systemctl stop $SERVICE_NAME
        echo -e "${GREEN}✅ 服务已停止${NC}"
    else
        echo -e "${YELLOW}⚠️ 服务未运行${NC}"
    fi
}

# 拉取最新代码
pull_updates() {
    echo -e "${BLUE}📥 拉取最新代码...${NC}"

    cd "$APP_DIR" || exit 1

    # 检查是否有未提交的更改
    if [ -n "$(git status --porcelain)" ]; then
        echo -e "${YELLOW}⚠️ 检测到本地修改，将自动保存...${NC}"
        git stash push -m "Auto stash before update $(date)"
    fi

    # 拉取最新代码
    git pull origin master

    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✅ 代码更新成功${NC}"
    else
        echo -e "${RED}❌ 代码更新失败${NC}"
        exit 1
    fi
}

# 安装依赖
install_dependencies() {
    echo -e "${BLUE}📚 检查并安装依赖...${NC}"

    cd "$APP_DIR" || exit 1

    # 激活虚拟环境
    if [ -f "venv/bin/activate" ]; then
        source venv/bin/activate
        echo -e "${GREEN}✅ 虚拟环境已激活${NC}"
    else
        echo -e "${RED}❌ 虚拟环境不存在${NC}"
        exit 1
    fi

    # 安装依赖
    pip install -r requirements.txt

    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✅ 依赖安装完成${NC}"
    else
        echo -e "${RED}❌ 依赖安装失败${NC}"
        exit 1
    fi
}

# 启动服务
start_service() {
    echo -e "${BLUE}🚀 启动服务...${NC}"

    sudo systemctl start $SERVICE_NAME

    # 等待服务启动
    sleep 3

    if systemctl is-active --quiet $SERVICE_NAME; then
        echo -e "${GREEN}✅ 服务启动成功${NC}"
    else
        echo -e "${RED}❌ 服务启动失败${NC}"
        echo -e "${YELLOW}查看日志: sudo journalctl -u $SERVICE_NAME -f${NC}"
        exit 1
    fi
}

# 验证部署
verify_deployment() {
    echo -e "${BLUE}🔍 验证部署...${NC}"

    # 等待服务完全启动
    sleep 5

    # 检查健康状态
    health_response=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:3003/health)

    if [ "$health_response" == "200" ]; then
        echo -e "${GREEN}✅ 健康检查通过${NC}"
    else
        echo -e "${RED}❌ 健康检查失败 (HTTP: $health_response)${NC}"
        return 1
    fi

    # 检查新的检验单查询接口
    inspection_response=$(curl -s -o /dev/null -w "%{http_code}" -X POST http://localhost:3003/mock/yonbip/QMS_QIT/checkapply/list -H "Content-Type: application/json" -d '{"pageIndex":1,"pageSize":5}')

    if [ "$inspection_response" == "200" ]; then
        echo -e "${GREEN}✅ 检验单查询接口正常${NC}"
    else
        echo -e "${RED}❌ 检验单查询接口异常 (HTTP: $inspection_response)${NC}"
        return 1
    fi

    echo -e "${GREEN}🎉 部署验证通过！${NC}"
    return 0
}

# 显示部署结果
show_results() {
    echo ""
    echo "=================================================="
    echo -e "${GREEN}🎉 更新部署完成！${NC}"
    echo "=================================================="
    echo -e "📊 服务状态: ${GREEN}$(systemctl is-active $SERVICE_NAME)${NC}"
    echo -e "🌐 Web管理界面: ${BLUE}http://your-server-ip:3003/admin${NC}"
    echo -e "🔍 健康检查: ${BLUE}http://your-server-ip:3003/health${NC}"
    echo -e "📋 检验管理: ${BLUE}新增检验单查询功能已就绪${NC}"
    echo ""
    echo -e "${YELLOW}💡 提示:${NC}"
    echo "• 访问Web界面可查看新的'检验管理'标签页"
    echo "• 新增API接口: POST /mock/yonbip/QMS_QIT/checkapply/list"
    echo "• 新增API接口: GET /mock/yonbip/QMS_QIT/checkapply/detail"
    echo ""
    echo -e "${BLUE}📁 备份位置: $BACKUP_DIR${NC}"
    echo -e "${BLUE}📝 查看日志: sudo journalctl -u $SERVICE_NAME -f${NC}"
}

# 回滚函数
rollback() {
    echo -e "${RED}🔄 开始回滚...${NC}"

    sudo systemctl stop $SERVICE_NAME

    # 恢复备份
    if [ -d "$BACKUP_DIR" ]; then
        cp -r "$BACKUP_DIR"/* "$APP_DIR/"
        echo -e "${GREEN}✅ 文件已恢复${NC}"
    fi

    sudo systemctl start $SERVICE_NAME
    echo -e "${GREEN}✅ 回滚完成${NC}"
}

# 主函数
main() {
    echo -e "${BLUE}ERP Mock Server 更新部署工具${NC}"
    echo -e "${BLUE}更新内容: 检验单查询功能${NC}"
    echo ""

    check_root
    check_prerequisites
    create_backup
    stop_service
    pull_updates
    install_dependencies
    start_service

    if verify_deployment; then
        show_results
    else
        echo -e "${RED}❌ 部署验证失败，是否需要回滚？ (y/n)${NC}"
        read -r response
        if [[ "$response" =~ ^[Yy]$ ]]; then
            rollback
        fi
        exit 1
    fi
}

# 捕获错误并提供回滚选项
trap 'echo -e "${RED}❌ 脚本执行出错，是否需要回滚？ (y/n)${NC}"; read response; if [[ "$response" =~ ^[Yy]$ ]]; then rollback; fi; exit 1' ERR

# 运行主函数
main "$@"